<?php

DEFINE('CODE_ALREADY_EXISTS', -409);

/**
 * Tools_GCalendarObject - Classe de gestion Google Calendar
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Tools_GCalendarObject extends Erra_Fields_Base_Object {

    public static $_client = null;

    /*
     * isGoogleEnabled() - Retourne 1 si google est potentiellement activé (si l'utilisateur et le mot de passe existent)
     */
    public static function isGoogleEnabled() {
        $login = Config_ConfigObject::get('login_google');
        $password = Config_ConfigObject::get('pwd_google');
        if (strlen($login) && strlen($password)) {
            return true;
        }
        return false;
    }

    public static function checkLogin($login, $password, $agenda_google = -1, $google_agenda_id = 'default') {
        $res = '';
        try {
            $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
            self::$_client = Zend_Gdata_ClientLogin::getHttpClient($login, $password, $service);
            self::saveGoogleAccess($login, $password, $agenda_google, $google_agenda_id);
            $result = self::enableSync($login, $password, $agenda_google, $google_agenda_id);

            if ($result['status'] == true) {
                $partialString = '(' . $result['success_records'] . ' enregistrements sur ' . $result['total_records'] . ' validés)';
                $res = Erra_Utils_Rest::Code_200_OK("L'agenda est desormais synchronisé avec Google Calendar ");
            } else {
                $partialString = '(' . $result['success_records'] . ' enregistrements sur ' . $result['total_records'] . ' validés)';
                $res = Erra_Utils_Rest::Code_200_OK("La synchronisation Google agenda est partiellement effectuée " . $partialString);
            }
        } catch (Zend_Gdata_App_Exception $e) {
            $res = Erra_Utils_Rest::Code_401_Unauthorized("Impossible de se connecter au compte Google");
        }
        echo $res;
    }

    public static function saveGoogleAccess($login, $password, $agenda_google = -1, $google_agenda_id = 'default') {
        $user_id = Access_ControlObject::get_user_id();
        if (strlen($password) && strlen($login)) {
            Erra_Core_DatabasePdo::EXECUTE('UPDATE config_configobject SET login_google="' . $login . '", pwd_google ="' . __crypt($password) . '", agenda_google="' . $agenda_google . '", google_agenda_id="' . $google_agenda_id . '" WHERE user_id=' . $user_id);
        } else {
            Erra_Core_DatabasePdo::EXECUTE('UPDATE config_configobject SET login_google="' . $login . '", pwd_google ="' . $password . '", agenda_google="' . $agenda_google . '", google_agenda_id="' . $google_agenda_id . '" WHERE user_id=' . $user_id);
        }
    }

    public static function enableSync($login, $password, $agenda_google = -1, $google_agenda_id = 'default') {
        $full_sync = true;
        $sumRecords = 0;
        $successRecords = 0;

        if (self::$_client == null) {
            $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
            self::$_client = Zend_Gdata_ClientLogin::getHttpClient($login, $password, $service);
        }

        if (is_numeric($agenda_google) && $agenda_google > -1) {
            // Check if agenda id has changed
            $user_id = Access_ControlObject::get_user_id();
            $queryResult = Erra_Core_DatabasePdo::SELECT('SELECT * FROM google_sync WHERE user_id=' . $user_id);
            $insertEvents = true;
            if (Erra_Core_DatabasePdo::rowCount() && is_object($queryResult)) {
                while ($result = $queryResult->fetch()) {
                    if ($result->event_agenda_id == $agenda_google) {
                        $insertEvents = false;
                    }
                }
            }
            //if ($insertEvents == true) {
            // Delete events for this agenda on google
            $queryExistingEvents = Erra_Core_DatabasePdo::SELECT('SELECT * FROM google_sync WHERE user_id=' . $user_id);
            if (Erra_Core_DatabasePdo::rowCount() && is_object($queryExistingEvents)) {
                while ($eventToDelete = $queryExistingEvents->fetch()) {
                    self::deleteEvent($eventToDelete->event_google_id);
                }
            }
            // Select all future events
            $eventQuery = Erra_Core_DatabasePdo::SELECT('SELECT prestation_name, msa_slotobject.event_id, msa_locationobject.nom, msa_locationobject.adresse, msa_clientobject.nom AS nom_client, msa_clientobject.prenom AS prenom_client, msa_locationobject.ville_cp, slot_day, slot_start, duree, description_courte_prestation FROM msa_slotobject, msa_prestationobject, msa_locationobject, msa_clientobject, msa_agendaobject WHERE slot_day > ' . (int) (time() - (3600 * 24)) . ' AND agenda_id=' . $agenda_google . ' AND msa_slotobject.prestation_id=msa_prestationobject.id AND msa_slotobject.agenda_id=msa_agendaobject.id AND msa_locationobject.id=msa_agendaobject.location AND msa_clientobject.id=msa_slotobject.client_id');
            while ($result = $eventQuery->fetch()) {
                $sumRecords++;
                $title = $result->prestation_name . ' - ' . $result->nom_client . ' ' . $result->prenom_client;
                $where = $result->adresse . ' ' . $result->ville_cp;
                $start_date = $result->slot_day + $result->slot_start;
                $end_date = $start_date + ($result->duree * 60);
                $description = $result->description_courte_prestation;
                $uniqid = $result->event_id;
                $event_id = self::insertEvent($title, $where, $description, $start_date, $end_date, $uniqid, $google_agenda_id);
                // Insert into Matching table event 
                if (!is_numeric($event_id) && $event_id != CODE_ALREADY_EXISTS) {
                    Erra_Core_DatabasePdo::EXECUTE('INSERT INTO google_sync(user_id, event_agenda_id, event_uniqid, event_google_id) VALUES("' . $user_id . '", "' . $agenda_google . '", "' . $uniqid . '", "' . $event_id . '")');
                    $successRecords++;
                } else {
                    if ($event_id != CODE_ALREADY_EXISTS) {
                        $full_sync = false;
                    } else {
                        $successRecords++;
                    }
                }
            }
        }
        // }
        return array('status' => $full_sync, 'total_records' => $sumRecords, 'success_records' => $successRecords);
    }

    public static function deleteEvent($eventId) {
        if (self::$_client == null) {
            $login = Config_ConfigObject::get('login_google');
            $password = __decrypt(Config_ConfigObject::get('pwd_google'));
            $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
            self::$_client = Zend_Gdata_ClientLogin::getHttpClient($login, $password, $service);
        }
        $gdataCal = new Zend_Gdata_Calendar(self::$_client);

        try {
            $event = $gdataCal->getCalendarEventEntry($eventId);
            Erra_Core_DatabasePdo::EXECUTE('DELETE FROM google_sync WHERE event_google_id ="' . $eventId . '"');
            if (is_object($event)) {
                $event->delete();
            }
        } catch (Zend_Exception $e) {
            //echo "Error: " . $e->getMessage();
        }
    }

    public static function editEvent($eventId, $msa_event) {
        if (self::$_client == null) {
            $login = Config_ConfigObject::get('login_google');
            $password = __decrypt(Config_ConfigObject::get('pwd_google'));
            $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
            self::$_client = Zend_Gdata_ClientLogin::getHttpClient($login, $password, $service);
        }

        $gdataCal = new Zend_Gdata_Calendar(self::$_client);
        try {
            $event = $gdataCal->getCalendarEventEntry($eventId);
            if (is_object($event)) {
                $title = $msa_event->prestation_name . ' - ' . $msa_event->nom_client . ' ' . $msa_event->prenom_client;
                $where = $msa_event->adresse . ' ' . $msa_event->ville_cp;
                $start_date = $msa_event->slot_day + $msa_event->slot_start;
                $end_date = $start_date + ($msa_event->duree * 60);
                $description = $msa_event->description_courte_prestation;

                $tzOffset = '+01';
                $event->title = $gdataCal->newTitle($title);
                $event->where = array($gdataCal->newWhere($where));
                $event->content = $gdataCal->newContent($description);
                $when = $gdataCal->newWhen();
                $when->startTime = "{$start_date}:00.000{$tzOffset}:00";
                $when->endTime = "{$end_date}:00.000{$tzOffset}:00";
                $event->when = array($when);
                $event->save();
                var_dump($event);
            }
        } catch (Zend_Exception $e) {
            //echo "Error: " . $e->getMessage();
        }
    }

    public static function editEventFromUniqId($uniqid) {
        if (self::isGoogleEnabled()) {
            $eventIdQuery = Erra_Core_DatabasePdo::SELECT('SELECT * FROM google_sync WHERE event_uniqid="' . $uniqid . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $eventIdQuery = $eventIdQuery->fetch();
                $eventId = $eventIdQuery->event_google_id;
                $eventQuery = Erra_Core_DatabasePdo::SELECT('SELECT prestation_name, msa_slotobject.event_id, msa_locationobject.nom, msa_locationobject.adresse, msa_clientobject.nom AS nom_client, msa_clientobject.prenom AS prenom_client, msa_locationobject.ville_cp, slot_day, slot_start, duree, description_courte_prestation FROM msa_slotobject, msa_prestationobject, msa_locationobject, msa_clientobject, msa_agendaobject WHERE msa_slotobject.event_id="' . $uniqid . '" AND msa_slotobject.prestation_id=msa_prestationobject.id AND msa_slotobject.agenda_id=msa_agendaobject.id AND msa_locationobject.id=msa_agendaobject.location AND msa_clientobject.id=msa_slotobject.client_id');
                if (Erra_Core_DatabasePdo::rowCount()) {
                    $result = $eventQuery->fetch();
                    if (strlen($eventId)) {
                        self::editEvent($eventId, $result);
                    }
                }
            }
        }
    }

    public static function deleteEventFromUniqid($uniqid) {
        if (self::isGoogleEnabled()) {
            $eventIdQuery = Erra_Core_DatabasePdo::SELECT('SELECT * FROM google_sync WHERE event_uniqid="' . $uniqid . '"');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $eventIdQuery = $eventIdQuery->fetch();
                $eventId = $eventIdQuery->event_google_id;
                if (strlen($eventId)) {
                    self::deleteEvent($eventId);
                }
            }
        }
    }

    public static function addEventFromUniqId($uniqid) {
        if (self::isGoogleEnabled()) {
            $user_id = Access_ControlObject::get_user_id();
            $google_agenda_id = Config_ConfigObject::get('google_agenda_id');
            $google_agenda_id = strlen($google_agenda_id) ? $google_agenda_id : 'default';
            $agenda_google = Config_ConfigObject::get('agenda_google');

            $eventQuery = Erra_Core_DatabasePdo::SELECT('SELECT prestation_name, msa_slotobject.event_id, msa_locationobject.nom, msa_locationobject.adresse, msa_clientobject.nom AS nom_client, msa_clientobject.prenom AS prenom_client, msa_locationobject.ville_cp, slot_day, slot_start, duree, description_courte_prestation FROM msa_slotobject, msa_prestationobject, msa_locationobject, msa_clientobject, msa_agendaobject WHERE msa_slotobject.event_id="' . $uniqid . '" AND msa_slotobject.prestation_id=msa_prestationobject.id AND msa_slotobject.agenda_id=msa_agendaobject.id AND msa_locationobject.id=msa_agendaobject.location AND msa_clientobject.id=msa_slotobject.client_id');
            if (Erra_Core_DatabasePdo::rowCount()) {
                $result = $eventQuery->fetch();
                $title = $result->prestation_name . ' - ' . $result->nom_client . ' ' . $result->prenom_client;
                $where = $result->adresse . ' ' . $result->ville_cp;
                $start_date = $result->slot_day + $result->slot_start;
                $end_date = $start_date + ($result->duree * 60);
                $description = $result->description_courte_prestation;
                $uniqid = $result->event_id;
                $event_id = self::insertEvent($title, $where, $description, $start_date, $end_date, $uniqid, $google_agenda_id);
                // Insert into Matching table event
                Erra_Core_DatabasePdo::EXECUTE('INSERT INTO google_sync(user_id, event_agenda_id, event_uniqid, event_google_id) VALUES("' . $user_id . '", "' . $agenda_google . '", "' . $uniqid . '", "' . $event_id . '")');
            }
        }
    }

    public static function insertEvent($title, $where, $description, $start_date, $end_date, $uniqid, $calendar_user = 'default') {
        // parameters
        // Avoid duplicates
        $calendar_user = strlen($calendar_user) ? urlencode($calendar_user) : 'default';


        $event_id = 0;
        $eventAlreadyInserted = Erra_Core_DatabasePdo::SELECT('SELECT COUNT(id) AS event_count FROM google_sync WHERE event_uniqid="' . $uniqid . '"')->fetch();
        if ($eventAlreadyInserted->event_count == 0) {
            try {
                $start_date = date('Y-m-d H:i', $start_date);
                $end_date = date('Y-m-d H:i', $end_date);

                $tzOffset = '+01'; // timezone offset
// build event
                $start_date = str_replace(' ', 'T', $start_date);
                $end_date = str_replace(' ', 'T', $end_date);
                if (self::$_client == null) {
                    $login = Config_ConfigObject::get('login_google');
                    $password = __decrypt(Config_ConfigObject::get('pwd_google'));
                    $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
                    self::$_client = Zend_Gdata_ClientLogin::getHttpClient($login, $password, $service);
                }
                $gdataCal = new Zend_Gdata_Calendar(self::$_client);
                $newEvent = $gdataCal->newEventEntry();

                $newEvent->title = $gdataCal->newTitle($title);
                $newEvent->where = array($gdataCal->newWhere($where));
                $newEvent->content = $gdataCal->newContent($description);

                $when = $gdataCal->newWhen();
                $when->startTime = "{$start_date}:00.000{$tzOffset}:00";
                $when->endTime = "{$end_date}:00.000{$tzOffset}:00";
                $newEvent->when = array($when);

                $createdEvent = $gdataCal->insertEvent($newEvent, "http://www.google.com/calendar/feeds/$calendar_user/private/full");
                // event id
                $event_id = $createdEvent->id->text;
            } catch (Zend_Gdata_App_Exception $e) {
                echo $e;
            }
            // insert event
            return $event_id;
        }
        return CODE_ALREADY_EXISTS;
    }

}
?>